package com.moyq5.spring.boot.app.register.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

/**
 * 
 * @author Moyq5
 * @date 2019年3月4日
 */
@Component
public class AppInfoNotifyGateway {
	
	private static final String CLIENT_ID = AppInfoNotifyGateway.class.getSimpleName() + String.valueOf(Math.round(Math.random() * 1e15));
	@Autowired
	private MqttPahoClientFactory clientFactory;
	
	@Bean
	public MessageChannel appInfoNotifyChannel() {
		return new DirectChannel();
	}
	
	@Bean
	@ServiceActivator(inputChannel = "appInfoNotifyChannel")
	public MessageHandler appInfoNotifyHandler() {
		MqttPahoMessageHandler handler = new MqttPahoMessageHandler(CLIENT_ID, clientFactory);
		handler.setAsync(false);
		handler.setDefaultQos(0);
		handler.setDefaultRetained(false);
		handler.setDefaultTopic("app/info/to/app");
		return handler;
	}

	@MessagingGateway(defaultRequestChannel = "appInfoNotifyChannel")
    public interface Gateway {
        void send(Message<?> message);
    }
	
}
